<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';
  import { Message } from '@garco-design/web-vue';
  import { createBusinessModelList,editBusinessModelList } from "@/api/cluserMgmt"

  const emits = defineEmits(['change']);

  const formRef = ref();

  const visible = ref(false);

  const generateFormModel = () => {
    return {
      id: null,
      type: 0,
      name: '',
      pid: null
    };
  };

  const formRules = reactive({
    name: [{ required: true, message: '请输入名称' }],
    type: [{ required: true, message: '请选择类型' }],
  });

  const formModel = ref(generateFormModel());
  const okLoading = ref(false);

  const typeLabel = computed(() =>
    formModel.value.type === 1 ? '数据中心' : '网络功能区'
  );
  const title = computed(() =>
    formModel.value.id ? `编辑${typeLabel.value}` : `创建${typeLabel.value}`
  );
  const show = async (record: any) => {
    console.log(record);
    formModel.value.type = record.type;
    formModel.value.pid = record.parent || 0;
    if (record.id) {
      formModel.value.id = record.id;
      formModel.value.name = record.name;
    }
    visible.value = true;
  };

  const handleCancel = () => {
    formModel.value = generateFormModel();
    formRef.value.clearValidate();
  };

  const handleBeforeOk = (done: any) => {
    formRef.value.validate(async (error: any) => {
      try {
        if (!error) {
          if (formModel.value.id) {
            var {code} = await editBusinessModelList(formModel.value.id, formModel.value);
          } else {
            var {code} = await createBusinessModelList(formModel.value);
          }
          if(code === 20000)Message.success('操作成功');
          emits('change');
          done();
        } else {
          done(false);
        }
      } catch (e) {
        console.log(e);
        done(false);
      }
    });
  };

  defineExpose({ show });
</script>

<template>
  <ga-modal
    v-model:visible="visible"
    :title="title"
    title-align="start"
    :ok-loading="okLoading"
    @close="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <ga-form ref="formRef" :model="formModel" autocomplete="off" :rules="formRules">
      <ga-form-item label="类型" field="type" validate-trigger="change">
        <ga-select v-model="formModel.type" disabled>
          <ga-option :value='1' label="数据中心"></ga-option>
          <ga-option :value='2' label="网络功能区"></ga-option>
        </ga-select>
      </ga-form-item>
      <ga-form-item label="名称" field="name" :validate-trigger="['change']">
        <ga-input placeholder="请输入名称" v-model="formModel.name" class="gt-input" />
      </ga-form-item>
    </ga-form>
  </ga-modal>
</template>

<style scoped lang="less"></style>
